using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Xsl;
using Code5Systems.FormMaster.Business;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;

namespace Code5Systems.FormMaster
{

	public partial class FormMaster : PortalModuleBase
	{
		//Implements IActionable
		//Implements IPortable
		
		//Sends the results of the Form Submission to the specified email recipient.
		private bool SendFormEmail(string sendTo, string sendFrom, XDocument resultsDoc)
		{
			string SMTPServer = string.Empty;
			string SMTPAuthentication = string.Empty;
			string SMTPUsername = string.Empty;
			string SMTPPassword = string.Empty;
			bool SMTPEnableSSL = Null.NullBoolean;
			string strBody = default(string);
			bool bSuccess = true;
			
			try
			{
				//Take out the Underscores which are required for the report transformation
				//but look bad in the email.
				if (_objFormSettings.ExcludeFieldsHiddenByFieldRulesInEmails)
				{
					List<XElement> fieldsToRemove = new List<XElement>();
					foreach (XElement xField in resultsDoc.Root.Descendants("Field"))
					{
						if (xField.Attribute("DisabledByFieldRule") != null)
						{
							fieldsToRemove.Add(xField);
						}
					}
					
					foreach (XElement field in fieldsToRemove)
					{
						field.Remove();
					}
				}
				
				foreach (XElement xQuestion in resultsDoc.Root.Descendants("Field").Elements("Question"))
				{
					xQuestion.Value = (string) (xQuestion.Value.Replace("_", " ").Trim());
				}
				
				strBody = GetEmailBody(_objResultsXmlDoc);
				
				if (!String.IsNullOrWhiteSpace(Host.SMTPServer))
				{
					SMTPServer = Host.SMTPServer;
				}
				
				if (!String.IsNullOrWhiteSpace(Host.SMTPAuthentication))
				{
					SMTPAuthentication = Host.SMTPAuthentication;
				}
				
				if (!String.IsNullOrWhiteSpace(Host.SMTPUsername))
				{
					SMTPUsername = Host.SMTPUsername;
				}
				
				if (!String.IsNullOrWhiteSpace(Host.SMTPPassword))
				{
					SMTPPassword = Host.SMTPPassword;
				}
				
				SMTPEnableSSL = Host.EnableSMTPSSL;

				string subject = _objFormInfo.FormName;
				
				if (this._objFormSettings.UseFieldForSubject)
				{
					if (_objFormSettings.AppendToSubject)
					{
						subject += this.GetSubject();
					}
					else
					{
						subject = this.GetSubject();
					}
				}
				else
				{
					subject = Localization.GetString("Subject", this.LocalResourceFile);
					if (subject != string.Empty)
					{
						subject += " " + _objFormInfo.FormName;
					}
					else
					{
						subject += _objFormInfo.FormName;
					}
				}
				
				System.Net.Mail.MailMessage objMail = new System.Net.Mail.MailMessage();
				
				objMail.From = new MailAddress(sendFrom);
				
				string strReplyTo = this.GetEmailReplyToAddress();
				if (!string.IsNullOrEmpty(strReplyTo))
				{
					objMail.ReplyToList.Add(strReplyTo);
				}
				
				Encoding encod = GetEncoding();
				
				objMail.SubjectEncoding = encod;
				
				System.Net.Mime.ContentType htmlType = new System.Net.Mime.ContentType("text/html");
				System.Net.Mime.ContentType txtType = new System.Net.Mime.ContentType("text/plain");
				
				if (_objFormSettings.SendHtmlEmail || _objFormSettings.TemplateType == Code5Systems.FormMaster.Business.TemplateType.Custom)
				{
					objMail.IsBodyHtml = true;
					if (_objFormSettings.SendMultipart)
					{
						AlternateView AltHtml = default(AlternateView);
						AlternateView AltText = default(AlternateView);
						
						AltHtml = AlternateView.CreateAlternateViewFromString(strBody, encod, "text/html");
						AltHtml.ContentType = htmlType;
						AltHtml.ContentType.CharSet = encod.WebName;
						AltHtml.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
						objMail.AlternateViews.Add(AltHtml);
						
						AltText = AlternateView.CreateAlternateViewFromString(this.GetTextEmailBody(_objResultsXmlDoc, true), encod, "text/plain");
						AltText.ContentType = txtType;
						AltText.ContentType.CharSet = encod.WebName;
						AltText.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
						objMail.AlternateViews.Add(AltText);
					}
					else
					{
						objMail.BodyEncoding = encod;
						objMail.Body = strBody;
					}
				}
				else
				{
					objMail.IsBodyHtml = false;
					objMail.BodyEncoding = encod;
					objMail.Body = strBody;
				}
				
				objMail.Subject = subject;
				
				// external SMTP server
				int SmtpPort = Null.NullInteger;
				int portPos = SMTPServer.IndexOf(":");
				if (portPos > -1)
				{
					SmtpPort = int.Parse(SMTPServer.Substring(portPos + 1, SMTPServer.Length - portPos - 1));
				}
				
				System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
				
				if (SMTPServer != "")
				{
					
					//Port Code Fix Submitted by Brad Murray - Thanks Brad
					if (SmtpPort > Null.NullInteger)
					{
						smtpClient.Host = SMTPServer.Replace(":" + SmtpPort.ToString(), "");
						smtpClient.Port = SmtpPort;
					}
					else
					{
						smtpClient.Host = SMTPServer;
					}
					
					switch (SMTPAuthentication)
					{
						case "": // anonymous
						case "0":
							break;
						case "1": // basic
							if (SMTPUsername != "" && SMTPPassword != "")
							{
								smtpClient.Credentials = new System.Net.NetworkCredential(SMTPUsername, SMTPPassword);
							}
							break;
						case "2": // NTLM
							smtpClient.UseDefaultCredentials = true;
							break;
					}
				}
				
				smtpClient.EnableSsl = SMTPEnableSSL;
				
				//objMail.Body = strBody
				
				if (_objFormInfo.ShowCcMe)
				{
					CheckBox chkCcMe = null;

					if (this._objFormCtl.Pages.Count == 1)
					{
						chkCcMe = (CheckBox)(this.FindControl("chkCcMe"));
					}
					else
					{
						chkCcMe = (CheckBox)(this.phForm.FindControl("chkCcMe"));
					}

					if (chkCcMe != null)
					{
						if (chkCcMe.Checked)
						{
							objMail.To.Add(this.GetEmailCcMeAddress());
							smtpClient.Send(objMail);
							objMail.To.Clear();
						}
					}
				}
				
				string[] aryAddress = sendTo.Split(';');
				foreach (string send in aryAddress)
				{
					objMail.To.Add(send);
				}
				
				if (_objFormInfo.BccAddress != string.Empty)
				{
					aryAddress = _objFormInfo.BccAddress.Split(';');
					foreach (string send in aryAddress)
					{
						objMail.Bcc.Add(send);
					}
				}
				
				// Attach the Specified Files to the Email
				XElement xAttachPath = default(XElement);
				XElement xFileName = default(XElement);
				XElement xFileDataId = default(XElement);
				FileStream ifStream = default(FileStream);
				Code5Systems.FormMaster.Business.FormFileDataController objFileDataCtl = null;
				Code5Systems.FormMaster.Business.FormFileDataInfo objFileInfo = default(Code5Systems.FormMaster.Business.FormFileDataInfo);
				
				IEnumerable<XElement> xFiles = resultsDoc.Root.Descendants("AttachFile");
				
				foreach (XElement atchFile in xFiles)
				{
					
					//oFileDataId = fileNode.SelectSingleNode("FileDataId")
					xFileDataId = atchFile.Element("FileDataId");
					if (xFileDataId != null)
					{
						if (objFileDataCtl == null)
						{
							objFileDataCtl = new Code5Systems.FormMaster.Business.FormFileDataController();
						}
						objFileInfo = objFileDataCtl.Get(Convert.ToInt32(xFileDataId.Value));
						if (objFileInfo != null)
						{
							MemoryStream memStrm = new MemoryStream(objFileInfo.FileData);
							objMail.Attachments.Add(new Attachment(memStrm, objFileInfo.OrigFileName));
						}
						
					}
					else
					{
						xAttachPath = atchFile.Element("AttachPath");
						xFileName = atchFile.Element("FileName");
						if (xAttachPath != null)
						{
							if (xFileName != null)
							{
								if (File.Exists(xAttachPath.Value))
								{
									ifStream = new FileStream(xAttachPath.Value, FileMode.Open, FileAccess.Read);
									objMail.Attachments.Add(new Attachment(ifStream, xFileName.Value));
								}
							}
						}
					}
				}
				
				smtpClient.Send(objMail);
				
				// Close all Open File Attachment Streams
				foreach (Attachment attachment in objMail.Attachments)
				{
					attachment.ContentStream.Close();
				}
				
				// Clean up the Temporary Files used as Attachements
				foreach (XElement atchFile in xFiles)
				{
					xAttachPath = atchFile.Element("AttachPath");
					if (xAttachPath != null)
					{
						if (File.Exists(xAttachPath.Value))
						{
							File.Delete(xAttachPath.Value);
						}
					}
				}
				
				
			}
			catch (HttpException exHttp)
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, exHttp.GetBaseException().Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				Exceptions.LogException(exHttp);
				bSuccess = false;
				_postResult = Code5Systems.FormMaster.Business.FormPostResult.FailedEmail;
			}
			catch (Exception exc)
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, exc.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				Exceptions.LogException(exc);
				_postResult = Code5Systems.FormMaster.Business.FormPostResult.FailedEmail;
			}
			
			return bSuccess;
			
		}
		
		private string GetEmailBody(XDocument objResults)
		{
			StringBuilder sbBody = new StringBuilder();
			string strBody = "";
			
			if (_objFormSettings.SendHtmlEmail)
			{
				IEnumerable<XElement> xAnswers = objResults.Descendants("Answer");
				foreach (XElement answer in xAnswers)
				{
					answer.Value = answer.Value.Replace(Environment.NewLine, "<br/>");
				}
			}
			
			
			foreach (string validator in _disabledValidators)
			{
				
			}
			
			switch (_objFormSettings.TemplateType)
			{
				case Code5Systems.FormMaster.Business.TemplateType.XSL:
					string strXsltPath = default(string);
					XslCompiledTransform oTransDoc = default(XslCompiledTransform);
					XsltArgumentList oXsltArg = default(XsltArgumentList);
					StringWriter strStream = default(StringWriter);
					
					strXsltPath = "assets/xslt/EmailSend.xslt";
					
					if (_objFormSettings.SendHtmlEmail)
					{
						strXsltPath = "assets/xslt/EmailSendHtml.xslt";
					}
					
					if (_objFormSettings.UseCustomXslt)
					{
						if (_objFormSettings.SendHtmlEmail)
						{
							strXsltPath = "assets/xslt/" + PortalId + "/" + ModuleId + "/EmailSendHtml.xslt";
						}
						else
						{
							strXsltPath = "assets/xslt/" + PortalId + "/" + ModuleId + "/EmailSend.xslt";
						}
					}
					
					if (!_objFormSettings.SendHtmlEmail)
					{
						IEnumerable<XElement> xAnswers = objResults.Descendants("Answer");
						foreach (XElement answer in xAnswers)
						{
							answer.Value = Utility.GetTextModeUrl(answer.Value);
						}
					}
					
					NameTable nt = new NameTable();
					
					XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
					nsmgr.AddNamespace("", "");
					
					//Create the XmlParserContext.
					XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
					
					oTransDoc = new XslCompiledTransform();
					oXsltArg = new XsltArgumentList();
					oTransDoc.Load(Server.MapPath(this.ControlPath + strXsltPath));
					
					strStream = new StringWriter();
					
					XmlWriterSettings settings = new XmlWriterSettings();
					settings.OmitXmlDeclaration = false;
					settings.ConformanceLevel = ConformanceLevel.Auto;
					settings.CloseOutput = false;
					
					oTransDoc.Transform(new XmlTextReader(objResults.ToString(), XmlNodeType.Document, context), oXsltArg, XmlWriter.Create(strStream, settings), null);
					
					sbBody.Append(strStream.ToString());
					
					strStream.Close();
					break;
					
				case Code5Systems.FormMaster.Business.TemplateType.Custom:
					XElement xCustomTemplate = default(XElement);
					
					//Find the Custom Template Element and set the editor control text property
					XDocument xformDoc = XDocument.Parse(this._objFormCtl.FormInfo.FormDefinition);
					xCustomTemplate = xformDoc.Root.Element("CustomTemplate");
					if (xCustomTemplate != null)
					{
						strBody = Server.HtmlDecode(System.Convert.ToString(xCustomTemplate.Value));
					}
					
					strBody = ReplaceTokens(objResults, strBody);
					
					sbBody.Append(strBody);
					break;
					
				default:
					sbBody.Append(this.GetTextEmailBody(objResults));
					break;
					
			}

			if (_objFormSettings.DataDirectLink && _objFormInfo.SaveData)
			{
				string url = DotNetNuke.Common.Globals.NavigateURL(this.TabId, "Dispatcher", "mid=" + this.ModuleId.ToString(), "fdid=" + this._formDataId.ToString(), "mctl=report");
				if (_objFormSettings.SendHtmlEmail)
				{
					sbBody.Append("<p>");
					sbBody.Append(String.Format("<a href=\"{0}\">{1}</a>", url, Localization.GetString("DataDirectLink", this.LocalResourceFile)));
					sbBody.Append("</p>");
				}
				else
				{
					sbBody.Append(Environment.NewLine + Environment.NewLine);
					sbBody.Append(Localization.GetString("DataDirectLink", this.LocalResourceFile) + ":");
					sbBody.Append(Environment.NewLine);
					sbBody.Append(url);
					sbBody.Append(Environment.NewLine);
				}
			}
			
			return sbBody.ToString();
			
		}
		
		private string GetTextEmailBody(XDocument objResults, bool forceTextFormat = false)
		{
			StringBuilder sbBody = new StringBuilder();
			string strTextPath = default(string);
			string strTempText = default(string);
			List<XElement> xFields = default(System.Collections.Generic.List<XElement>);
			XElement xQuestion = default(XElement);
			List<XElement> xAnswers = default(System.Collections.Generic.List<XElement>);
			string strFileExt = ".TXT";
			XElement xElem = default(XElement);
			
			strTextPath = Server.MapPath(this.ControlPath + "Templates/" + PortalId + "/" + _objFormSettings.TextTemplate.Trim());
			
			if (!Directory.Exists(strTextPath))
			{
				strTextPath = Server.MapPath(this.ControlPath + "Templates/" + _objFormSettings.TextTemplate.Trim());
			}
			
			if ((!forceTextFormat) && _objFormSettings.SendHtmlEmail)
			{
				strFileExt = ".HTM";
			}
			
			if (File.Exists(strTextPath + "\\HEADER" + strFileExt))
			{
				
				//Get the HEADER template file
				StreamReader iFile = File.OpenText(strTextPath + "\\HEADER" + strFileExt);
				strTempText = iFile.ReadToEnd();
				iFile.Close();
				
				//Replace the [TOKENS]
				strTempText = strTempText.Replace("[FORMNAME]", _objFormInfo.FormName);
				xElem = objResults.Root.Element("Submitted_By");
				if (xElem != null)
				{
					strTempText = strTempText.Replace("[SUBMITTEDBY]", xElem.Value);
				}
				else
				{
					strTempText = strTempText.Replace("[SUBMITTEDBY]", "");
				}
				
				sbBody.Append(strTempText);
				
				//Get the ITEM template file
				string strModText = default(string);
				string strAnswers = default(string);
				iFile = File.OpenText(strTextPath + "\\ITEM" + strFileExt);
				strTempText = iFile.ReadToEnd();
				iFile.Close();
				
				//For each Field in the Form, add a new ITEM template and replace the [TOKENS]
				xFields = objResults.Descendants("Field").ToList();
				
				for (int i = 0; i <= xFields.Count() - 1; i++)
				{
					xQuestion = xFields[i].Element("Question");
					strModText = strTempText.Replace("[QUESTION]", xQuestion.Value);
					xAnswers = xFields[i].Elements("Answers").Elements("Answer").ToList();
					strAnswers = "";
					for (int a = 0; a <= xAnswers.Count() - 1; a++)
					{
						strAnswers += (string) (xAnswers[a].Value);
						
						//If Sending Text Format strip anchor tags from any Uploaded files
						if (strAnswers.IndexOf("</a>") > -1)
						{
							if (!_objFormSettings.SendHtmlEmail)
							{
								strAnswers = Utility.GetTextModeUrl(strAnswers);
							}
						}
						
						if (a < xAnswers.Count - 1)
						{
							strAnswers += ", ";
						}
					}
					strModText = strModText.Replace("[ANSWER]", strAnswers);
					strModText += "\r\n";
					sbBody.Append(strModText);
				}
				
				//Get the FOOTER template file
				iFile = File.OpenText(strTextPath + "\\FOOTER" + strFileExt);
				strTempText = iFile.ReadToEnd();
				iFile.Close();
				
				//No [TOKENS] here
				sbBody.Append(strTempText);
			}
			
			return sbBody.ToString();
			
		}
		
		//Function to return the Email Recipient address based on the Form options
		//selected/entered in the Form Editor page for the CC Me Email Address
		private string GetEmailCcMeAddress()
		{
			string strEmailCcMe = string.Empty;
			Code5Systems.FormMaster.Business.FormControlInfo oFormControlInfo = default(Code5Systems.FormMaster.Business.FormControlInfo);
			
			Control oControl = default(Control);
			
			if (this._objFormCtl.Pages.Count == 1)
			{
				oControl = (Control)(this.FindControl(this._objFormInfo.EmailCcMeControl));
			}
			else
			{
				oControl = (Control)(this.phForm.FindControl(this._objFormInfo.EmailCcMeControl));
			}

			if (oControl != null)
			{
				oFormControlInfo = this._objFormCtl.GetFormControlInfo(this._objFormInfo, oControl.ID);
				switch (oControl.GetType().ToString())
				{
					case "System.Web.UI.WebControls.HiddenField":
						strEmailCcMe = ((System.Web.UI.WebControls.HiddenField) oControl).Value;
						
						if (oFormControlInfo.EncryptField)
						{
							strEmailCcMe = Utility.DecryptString(strEmailCcMe);
						}
						
						if (!Utility.ValidateEmailAddressFormat(strEmailCcMe))
						{
							strEmailCcMe = "";
						}
						break;
					case "System.Web.UI.WebControls.DropDownList":
						strEmailCcMe = ((System.Web.UI.WebControls.DropDownList) oControl).SelectedValue;
						if (!Utility.ValidateEmailAddressFormat(strEmailCcMe))
						{
							strEmailCcMe = "";
						}
						break;
						
					case "System.Web.UI.WebControls.RadioButtonList":
						strEmailCcMe = ((System.Web.UI.WebControls.RadioButtonList) oControl).SelectedValue;
						if (!Utility.ValidateEmailAddressFormat(strEmailCcMe))
						{
							strEmailCcMe = "";
						}
						break;
						
					case "System.Web.UI.WebControls.TextBox":
						strEmailCcMe = ((System.Web.UI.WebControls.TextBox) oControl).Text;
						if (!Utility.ValidateEmailAddressFormat(strEmailCcMe))
						{
							strEmailCcMe = "";
						}
						break;
						
					case "System.Web.UI.WebControls.CheckBoxList":
						CheckBoxList oCheckBoxList = (CheckBoxList) oControl;
						ListItem oListItem = default(ListItem);
						foreach (ListItem tempLoopVar_oListItem in oCheckBoxList.Items)
						{
							oListItem = tempLoopVar_oListItem;
							if (oListItem.Selected)
							{
								if (strEmailCcMe.IndexOf(oListItem.Value) == -1)
								{
									if (Utility.ValidateEmailAddressFormat(oListItem.Value))
									{
										strEmailCcMe += oListItem.Value + ";";
									}
								}
							}
						}
						strEmailCcMe = strEmailCcMe.Substring(0, strEmailCcMe.Length - 1);
						break;
				}
			}
			
			return strEmailCcMe;
			
		}
		
		//Function to return the Email Recipient address based on the Form options
		//selected/entered in the Form Editor page for the Auto Response Email Address
		private string GetEmailAutoResponseAddress()
		{
			string strEmailAutoResponse = string.Empty;

			Control oControl = default(Control);
			
			if (this._objFormCtl.Pages.Count == 1)
			{
				oControl = (Control)(this.FindControl(_objFormSettings.AutoRespToField));
			}
			else
			{
				oControl = (Control)(this.phForm.FindControl(_objFormSettings.AutoRespToField));
			}
			
			if (oControl != null)
			{
				FormControlInfo oFormControlInfo = this._objFormCtl.GetFormControlInfo(this._objFormInfo, oControl.ID);

				switch (oControl.GetType().ToString())
				{
					case "System.Web.UI.WebControls.DropDownList":
						strEmailAutoResponse = ((System.Web.UI.WebControls.DropDownList) oControl).SelectedValue;
						if (!Utility.ValidateEmailAddressFormat(strEmailAutoResponse))
						{
							strEmailAutoResponse = "";
						}
						break;
						
					case "System.Web.UI.WebControls.RadioButtonList":
						strEmailAutoResponse = ((System.Web.UI.WebControls.RadioButtonList) oControl).SelectedValue;
						if (!Utility.ValidateEmailAddressFormat(strEmailAutoResponse))
						{
							strEmailAutoResponse = "";
						}
						break;
						
					case "System.Web.UI.WebControls.TextBox":
						strEmailAutoResponse = ((System.Web.UI.WebControls.TextBox) oControl).Text;
						if (!Utility.ValidateEmailAddressFormat(strEmailAutoResponse))
						{
							strEmailAutoResponse = "";
						}
						break;
						
					case "System.Web.UI.WebControls.CheckBoxList":
						CheckBoxList oCheckBoxList = (CheckBoxList) oControl;
						ListItem oListItem = default(ListItem);
						foreach (ListItem tempLoopVar_oListItem in oCheckBoxList.Items)
						{
							oListItem = tempLoopVar_oListItem;
							if (oListItem.Selected)
							{
								if (strEmailAutoResponse.IndexOf(oListItem.Value) == -1)
								{
									if (Utility.ValidateEmailAddressFormat(oListItem.Value))
									{
										strEmailAutoResponse += oListItem.Value + ";";
									}
								}
							}
						}
						strEmailAutoResponse = strEmailAutoResponse.Substring(0, strEmailAutoResponse.Length - 1);
						break;
					case "System.Web.UI.WebControls.HiddenField":
						strEmailAutoResponse = ((System.Web.UI.WebControls.HiddenField)oControl).Value;

						if (oFormControlInfo.EncryptField)
						{
							strEmailAutoResponse = Utility.DecryptString(strEmailAutoResponse);
						}

						if (!Utility.ValidateEmailAddressFormat(strEmailAutoResponse))
						{
							strEmailAutoResponse = "";
						}
						break;
				}
			}
			
			return strEmailAutoResponse;
			
		}
		
		//Function to return the Email Recipient address based on the Form options
		//selected/entered in the Form Editor page and sets the Class Scope bSendMail
		//value to false if either no sending was selected or no valid email address is found
		private string GetEmailSendtoAddress()
		{
			string strEmailSendTo = "";
			Code5Systems.FormMaster.Business.FormControlInfo oFormControlInfo = default(Code5Systems.FormMaster.Business.FormControlInfo);
			
			if (((Code5Systems.FormMaster.Business.FormInfo.EmailActionNone) _objFormInfo.EmailSendAction) == Code5Systems.FormMaster.Business.FormInfo.EmailActionNone.None)
			{
				_bSendMail = false;
			}
			else if (((Code5Systems.FormMaster.Business.FormInfo.EmailActionNone) _objFormInfo.EmailSendAction) == Code5Systems.FormMaster.Business.FormInfo.EmailActionNone.UseAdmin)
			{
				if (Utility.ValidateEmailAddressFormat(this.PortalSettings.Email))
				{
					strEmailSendTo = this.PortalSettings.Email;
				}
			}
			else if (((Code5Systems.FormMaster.Business.FormInfo.EmailActionNone) _objFormInfo.EmailSendAction) == Code5Systems.FormMaster.Business.FormInfo.EmailActionNone.UserDefined)
			{
				if (Utility.ValidateEmailAddressFormat(_objFormInfo.EmailSendTo))
				{
					strEmailSendTo = _objFormInfo.EmailSendTo;
				}
			}
			else if (((Code5Systems.FormMaster.Business.FormInfo.EmailActionNone) _objFormInfo.EmailSendAction) == Code5Systems.FormMaster.Business.FormInfo.EmailActionNone.UseForm)
			{
				Control oControl = default(Control);
				oControl = (Control) (this.FindControl(_objFormInfo.EmailSendToControl));
				
				if (oControl != null)
				{
					oFormControlInfo = this._objFormCtl.GetFormControlInfo(oControl.ID);
					
					switch (oControl.GetType().ToString())
					{
						case "System.Web.UI.WebControls.DropDownList":
							strEmailSendTo = ((System.Web.UI.WebControls.DropDownList) oControl).SelectedValue;
							
							if (oFormControlInfo.EncryptField)
							{
								strEmailSendTo = Utility.DecryptString(strEmailSendTo);
							}
							
							if (!Utility.ValidateEmailAddressFormat(strEmailSendTo))
							{
								strEmailSendTo = "";
							}
							break;
							
						case "System.Web.UI.WebControls.RadioButtonList":
							strEmailSendTo = ((System.Web.UI.WebControls.RadioButtonList) oControl).SelectedValue;
							
							if (oFormControlInfo.EncryptField)
							{
								strEmailSendTo = Utility.DecryptString(strEmailSendTo);
							}
							
							if (!Utility.ValidateEmailAddressFormat(strEmailSendTo))
							{
								strEmailSendTo = "";
							}
							break;
							
						case "System.Web.UI.WebControls.TextBox":
							strEmailSendTo = ((System.Web.UI.WebControls.TextBox) oControl).Text;
							
							if (oFormControlInfo.EncryptField)
							{
								strEmailSendTo = Utility.DecryptString(strEmailSendTo);
							}
							
							if (!Utility.ValidateEmailAddressFormat(strEmailSendTo))
							{
								strEmailSendTo = "";
							}
							break;
							
						case "System.Web.UI.WebControls.ListBox":
							ListBox oListBox = (ListBox) oControl;
							ListItem oListItem_1 = default(ListItem);
							foreach (ListItem tempLoopVar_oListItem_1 in oListBox.Items)
							{
								oListItem_1 = tempLoopVar_oListItem_1;
								if (oListItem_1.Selected)
								{
									
									if (oFormControlInfo.EncryptField)
									{
										oListItem_1.Value = Utility.DecryptString(oListItem_1.Value);
									}
									
									if (strEmailSendTo.IndexOf(oListItem_1.Value) == -1)
									{
										if (Utility.ValidateEmailAddressFormat(oListItem_1.Value))
										{
											if (!strEmailSendTo.Contains(oListItem_1.Value))
											{
												strEmailSendTo += oListItem_1.Value + ";";
											}
										}
									}
								}
							}
							strEmailSendTo = strEmailSendTo.Substring(0, strEmailSendTo.Length - 1);
							break;
							
						case "System.Web.UI.WebControls.CheckBoxList":
							CheckBoxList oCheckBoxList = (CheckBoxList) oControl;
							ListItem oListItem = default(ListItem);
							foreach (ListItem tempLoopVar_oListItem in oCheckBoxList.Items)
							{
								oListItem = tempLoopVar_oListItem;
								if (oListItem.Selected)
								{
									
									if (oFormControlInfo.EncryptField)
									{
										oListItem.Value = Utility.DecryptString(oListItem.Value);
									}
									
									if (strEmailSendTo.IndexOf(oListItem.Value) == -1)
									{
										if (Utility.ValidateEmailAddressFormat(oListItem.Value))
										{
											if (!strEmailSendTo.Contains(oListItem.Value))
											{
												strEmailSendTo += oListItem.Value + ";";
											}
										}
									}
								}
							}
							strEmailSendTo = strEmailSendTo.Substring(0, strEmailSendTo.Length - 1);
							break;
							
						case "System.Web.UI.WebControls.HiddenField":
							strEmailSendTo = ((System.Web.UI.WebControls.HiddenField) oControl).Value;
							
							if (oFormControlInfo.EncryptField)
							{
								strEmailSendTo = Utility.DecryptString(strEmailSendTo);
							}
							
							if (!Utility.ValidateEmailAddressFormat(strEmailSendTo))
							{
								strEmailSendTo = "";
							}
							break;
					}
				}
			}
			
			if (_bSendMail)
			{
				if (strEmailSendTo == string.Empty)
				{
					if (Utility.ValidateEmailAddressFormat(this.PortalSettings.Email))
					{
						strEmailSendTo = this.PortalSettings.Email;
						_strFormAdminErrorMsg += "No Valid Email Address could be found to send Form Results" + "\r\n";
					}
					
					if (strEmailSendTo == string.Empty)
					{
						_bSendMail = false;
					}
				}
			}
			
			return strEmailSendTo;
			
		}
		
		//Returns the Email From Address based on the options selected/entered
		//in the Form Editor Page and sets the Class Scope bSendMail
		//value to false if no valid email address is found
		private string GetEmailSendFromAddress()
		{
			string strEmailSendFrom = "";
			Code5Systems.FormMaster.Business.FormControlInfo oFormControlInfo = default(Code5Systems.FormMaster.Business.FormControlInfo);
			
			if (((Code5Systems.FormMaster.Business.FormInfo.EmailAction) _objFormInfo.EmailFromAction) == Code5Systems.FormMaster.Business.FormInfo.EmailAction.UseAdmin)
			{
				if (Utility.ValidateEmailAddressFormat(this.PortalSettings.Email))
				{
					strEmailSendFrom = this.PortalSettings.Email;
				}
			}
			else if (((Code5Systems.FormMaster.Business.FormInfo.EmailAction) _objFormInfo.EmailFromAction) == Code5Systems.FormMaster.Business.FormInfo.EmailAction.UserDefined)
			{
				if (Utility.ValidateEmailAddressFormat(_objFormInfo.FromAddress))
				{
					strEmailSendFrom = _objFormInfo.FromAddress;
				}
			}
			else if (((Code5Systems.FormMaster.Business.FormInfo.EmailAction) _objFormInfo.EmailFromAction) == Code5Systems.FormMaster.Business.FormInfo.EmailAction.UseForm)
			{
				Control oControl = default(Control);
				if (_objFormCtl.Pages.Count() > 1)
				{
					oControl = (Control)this.phForm.FindControl(_objFormInfo.EmailSendFromControl);
				}
				else
				{
					oControl = (Control)(this.FindControl(_objFormInfo.EmailSendFromControl));
				}
				
				if (oControl != null)
				{
					oFormControlInfo = this._objFormCtl.GetFormControlInfo(oControl.ID);
					
					switch (oControl.GetType().ToString())
					{
						case "System.Web.UI.WebControls.DropDownList":
							strEmailSendFrom = ((System.Web.UI.WebControls.DropDownList) oControl).SelectedValue;
							
							if (oFormControlInfo.EncryptField)
							{
								strEmailSendFrom = Utility.DecryptString(strEmailSendFrom);
							}
							
							if (!Utility.ValidateEmailAddressFormat(strEmailSendFrom))
							{
								strEmailSendFrom = "";
							}
							break;
							
						case "System.Web.UI.WebControls.RadioButtonList":
							strEmailSendFrom = ((System.Web.UI.WebControls.RadioButtonList) oControl).SelectedValue;
							
							if (oFormControlInfo.EncryptField)
							{
								strEmailSendFrom = Utility.DecryptString(strEmailSendFrom);
							}
							
							if (!Utility.ValidateEmailAddressFormat(strEmailSendFrom))
							{
								strEmailSendFrom = "";
							}
							break;
							
						case "System.Web.UI.WebControls.TextBox":
							strEmailSendFrom = ((System.Web.UI.WebControls.TextBox) oControl).Text;
							
							if (oFormControlInfo.EncryptField)
							{
								strEmailSendFrom = Utility.DecryptString(strEmailSendFrom);
							}
							
							if (!Utility.ValidateEmailAddressFormat(strEmailSendFrom))
							{
								strEmailSendFrom = "";
							}
							break;
							
						case "System.Web.UI.WebControls.CheckBoxList":
							CheckBoxList oCheckBoxList = (CheckBoxList) oControl;
							ListItem oListItem = default(ListItem);
							foreach (ListItem tempLoopVar_oListItem in oCheckBoxList.Items)
							{
								oListItem = tempLoopVar_oListItem;
								if (oListItem.Selected)
								{
									
									if (oFormControlInfo.EncryptField)
									{
										oListItem.Value = Utility.DecryptString(oListItem.Value);
									}
									
									if (strEmailSendFrom.IndexOf(oListItem.Value) == -1)
									{
										if (Utility.ValidateEmailAddressFormat(oListItem.Value))
										{
											strEmailSendFrom += oListItem.Value + ";";
										}
									}
								}
							}
							strEmailSendFrom = strEmailSendFrom.Substring(0, strEmailSendFrom.Length - 1);
							break;
							
						case "System.Web.UI.WebControls.HiddenField":
							strEmailSendFrom = ((System.Web.UI.WebControls.HiddenField) oControl).Value;
							
							if (oFormControlInfo.EncryptField)
							{
								strEmailSendFrom = Utility.DecryptString(strEmailSendFrom);
							}
							
							if (!Utility.ValidateEmailAddressFormat(strEmailSendFrom))
							{
								strEmailSendFrom = "";
							}
							break;
					}
					
				}
			}
			
			if (_bSendMail)
			{
				if (strEmailSendFrom == string.Empty)
				{
					if (Utility.ValidateEmailAddressFormat(this.PortalSettings.Email))
					{
						strEmailSendFrom = this.PortalSettings.Email;
						_strFormAdminErrorMsg += "No Valid Email Address could be found to send Form Results" + "\r\n";
					}
					
					if (strEmailSendFrom == string.Empty)
					{
						_bSendMail = false;
					}
				}
			}
			
			return strEmailSendFrom;
			
		}
		
		//Returns the Email ReplyTo Address based on the options selected/entered
		//in the Form Editor Page
		private string GetEmailReplyToAddress()
		{
			string strEmailReplyTo = "";
			Code5Systems.FormMaster.Business.FormControlInfo oFormControlInfo = default(Code5Systems.FormMaster.Business.FormControlInfo);
			
			if (((Code5Systems.FormMaster.Business.FormInfo.EmailActionNone) _objFormInfo.ReplyToAction) == Code5Systems.FormMaster.Business.FormInfo.EmailActionNone.None)
			{
			}
			else if (((Code5Systems.FormMaster.Business.FormInfo.EmailActionNone) _objFormInfo.ReplyToAction) == Code5Systems.FormMaster.Business.FormInfo.EmailActionNone.UseAdmin)
			{
				if (Utility.ValidateEmailAddressFormat(this.PortalSettings.Email))
				{
					strEmailReplyTo = this.PortalSettings.Email;
				}
			}
			else if (((Code5Systems.FormMaster.Business.FormInfo.EmailActionNone) _objFormInfo.ReplyToAction) == Code5Systems.FormMaster.Business.FormInfo.EmailActionNone.UserDefined)
			{
				if (Utility.ValidateEmailAddressFormat(_objFormInfo.FromAddress))
				{
					strEmailReplyTo = _objFormInfo.ReplyTo;
				}
			}
			else if (((Code5Systems.FormMaster.Business.FormInfo.EmailActionNone) _objFormInfo.ReplyToAction) == Code5Systems.FormMaster.Business.FormInfo.EmailActionNone.UseForm)
			{
				Control oControl = default(Control);
				if (_objFormCtl.Pages.Count() > 1)
				{
					oControl = (Control)this.phForm.FindControl(_objFormInfo.ReplyToControl);
				}
				else
				{
					oControl = (Control)(this.FindControl(_objFormInfo.ReplyToControl));
				}
				
				if (oControl != null)
				{
					oFormControlInfo = this._objFormCtl.GetFormControlInfo(oControl.ID);
					
					switch (oControl.GetType().ToString())
					{
						case "System.Web.UI.WebControls.DropDownList":
							strEmailReplyTo = ((System.Web.UI.WebControls.DropDownList) oControl).SelectedValue;
							
							if (oFormControlInfo.EncryptField)
							{
								strEmailReplyTo = Utility.DecryptString(strEmailReplyTo);
							}
							
							if (!Utility.ValidateEmailAddressFormat(strEmailReplyTo))
							{
								strEmailReplyTo = "";
							}
							break;
							
						case "System.Web.UI.WebControls.RadioButtonList":
							strEmailReplyTo = ((System.Web.UI.WebControls.RadioButtonList) oControl).SelectedValue;
							
							if (oFormControlInfo.EncryptField)
							{
								strEmailReplyTo = Utility.DecryptString(strEmailReplyTo);
							}
							
							if (!Utility.ValidateEmailAddressFormat(strEmailReplyTo))
							{
								strEmailReplyTo = "";
							}
							break;
							
						case "System.Web.UI.WebControls.TextBox":
							strEmailReplyTo = ((System.Web.UI.WebControls.TextBox) oControl).Text;
							
							if (oFormControlInfo.EncryptField)
							{
								strEmailReplyTo = Utility.DecryptString(strEmailReplyTo);
							}
							
							if (!Utility.ValidateEmailAddressFormat(strEmailReplyTo))
							{
								strEmailReplyTo = "";
							}
							break;
							
						case "System.Web.UI.WebControls.CheckBoxList":
							CheckBoxList oCheckBoxList = (CheckBoxList) oControl;
							ListItem oListItem_1 = default(ListItem);
							foreach (ListItem tempLoopVar_oListItem_1 in oCheckBoxList.Items)
							{
								oListItem_1 = tempLoopVar_oListItem_1;
								if (oListItem_1.Selected)
								{
									
									if (oFormControlInfo.EncryptField)
									{
										oListItem_1.Value = Utility.DecryptString(oListItem_1.Value);
									}
									
									if (strEmailReplyTo.IndexOf(oListItem_1.Value) == -1)
									{
										if (Utility.ValidateEmailAddressFormat(oListItem_1.Value))
										{
											strEmailReplyTo = oListItem_1.Value;
											goto endOfSelect;
										}
									}
								}
							}
							break;
							
						case "System.Web.UI.WebControls.ListBox":
							ListBox oListBox = (ListBox) oControl;
							ListItem oListItem = default(ListItem);
							foreach (ListItem tempLoopVar_oListItem in oListBox.Items)
							{
								oListItem = tempLoopVar_oListItem;
								if (oListItem.Selected)
								{
									
									if (oFormControlInfo.EncryptField)
									{
										oListItem.Value = Utility.DecryptString(oListItem.Value);
									}
									
									if (strEmailReplyTo.IndexOf(oListItem.Value) == -1)
									{
										if (Utility.ValidateEmailAddressFormat(oListItem.Value))
										{
											strEmailReplyTo = oListItem.Value;
											goto endOfSelect;
										}
									}
								}
							}
							break;
							
						case "System.Web.UI.WebControls.HiddenField":
							strEmailReplyTo = ((System.Web.UI.WebControls.HiddenField) oControl).Value;
							
							if (oFormControlInfo.EncryptField)
							{
								strEmailReplyTo = Utility.DecryptString(strEmailReplyTo);
							}
							
							if (!Utility.ValidateEmailAddressFormat(strEmailReplyTo))
							{
								strEmailReplyTo = "";
							}
							break;
					}
endOfSelect:
					1.GetHashCode() ; //VBConversions note: C# requires an executable line here, so a dummy line was added.
					
				}
			}
			
			return strEmailReplyTo;
			
		}
		
		//Function to return the Subject Line based on the Form options
		//selected/entered in the Form Editor page for the Subject Line
		private string GetSubject()
		{
			string strSubject = "";
			Control oControl = default(Control);
			Code5Systems.FormMaster.Business.FormControlInfo objTempFormControlInfo = default(Code5Systems.FormMaster.Business.FormControlInfo);
			List<Code5Systems.FormMaster.Business.FormControlInfo> aryFormCtlInfo = new List<Code5Systems.FormMaster.Business.FormControlInfo>();
			
			
			objTempFormControlInfo = this._objFormCtl.GetFormControlInfo(this._objFormInfo, this._objFormSettings.SubjectFieldValue);
			
			if (objTempFormControlInfo != null)
			{
				aryFormCtlInfo.Add(objTempFormControlInfo);
			}
			
			objTempFormControlInfo = this._objFormCtl.GetFormControlInfo(this._objFormInfo, this._objFormSettings.SubjectFieldValue2);
			
			if (objTempFormControlInfo != null)
			{
				aryFormCtlInfo.Add(objTempFormControlInfo);
			}
			
			foreach (Code5Systems.FormMaster.Business.FormControlInfo objFormControlInfo in aryFormCtlInfo)
			{
				oControl = this.FindControl(objFormControlInfo.ID) as Control;
				if (oControl != null)
				{
					switch (oControl.GetType().ToString())
					{
						case "System.Web.UI.WebControls.HiddenField":
							HtmlInputHidden hidden = oControl as HtmlInputHidden;
							if (hidden != null)
							{
								strSubject += hidden.Value;
							}
							break;
							
						case "System.Web.UI.WebControls.DropDownList":
							if (objFormControlInfo.ListItemToSave == Code5Systems.FormMaster.Business.FormController.ListItemToSave.Value)
							{
								strSubject += ((System.Web.UI.WebControls.DropDownList) oControl).SelectedValue;
							}
							else
							{
								strSubject += ((System.Web.UI.WebControls.DropDownList) oControl).SelectedItem.Text;
							}
							break;
							
						case "System.Web.UI.WebControls.RadioButtonList":
							if (objFormControlInfo.ListItemToSave == Code5Systems.FormMaster.Business.FormController.ListItemToSave.Value)
							{
								strSubject += ((System.Web.UI.WebControls.RadioButtonList) oControl).SelectedValue;
							}
							else
							{
								strSubject += ((System.Web.UI.WebControls.RadioButtonList) oControl).SelectedItem.Text;
							}
							break;
							
						case "System.Web.UI.WebControls.TextBox":
							strSubject += ((System.Web.UI.WebControls.TextBox) oControl).Text;
							break;
							
						case "System.Web.UI.WebControls.CheckBoxList":
							CheckBoxList oCheckBoxList = (CheckBoxList) oControl;
							ListItem oListItem = default(ListItem);
							string strListValue = default(string);
							
							foreach (ListItem tempLoopVar_oListItem in oCheckBoxList.Items)
							{
								oListItem = tempLoopVar_oListItem;
								if (oListItem.Selected)
								{
									if (objFormControlInfo.ListItemToSave == Code5Systems.FormMaster.Business.FormController.ListItemToSave.Value)
									{
										strListValue = oListItem.Value;
									}
									else
									{
										strListValue = oListItem.Text;
									}
									
									if (strSubject.IndexOf(strListValue) == -1)
									{
										strSubject += strListValue + ";";
									}
								}
							}
							
							strSubject = strSubject.Substring(0, strSubject.Length - 1);
							break;
					}
				}
				
				if (aryFormCtlInfo.Count > 1)
				{
					strSubject += " ";
				}
			}
			
			return strSubject;
			
		}
		
	}
	
}

